import store from '@/store/index'
import axios from 'axios'
import { createRouter, createWebHistory } from 'vue-router'
const routerHistory = createWebHistory()
const SignUp = () => import('../views/Signup.vue')
const CreatePost = () => import('../views/CreatePost.vue')
const Home = () => import('../views/Home.vue')
const Login = () => import('../views/Login.vue')
const ColumnDetail = () => import('../views/ColumnDetail.vue')
const router = createRouter({
  history: routerHistory,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      meta: { isShow: true }
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: { redirectAlreadyLogin: true, isShow: false }
    },
    {
      path: '/signup',
      name: 'signup',
      component: SignUp,
      meta: { redirectAlreadyLogin: true, isShow: false }
    },
    {
      path: '/column/:id',
      name: 'column',
      component: ColumnDetail,
      meta: { isShow: true }
    },
    {
      path: '/create',
      name: 'create',
      component: CreatePost,
      meta: { requiredLogin: true }
    },
    {
      path: '/posts/:id',
      name: 'post',
      component: () => import('@/views/PostDetail.vue')
    }
  ]
})
// router.beforeEach(async (to, from, next) => {
//   if (to.meta.requiredLogin && !store.state.user.isLogin) {
//     // 需要登陆，但没登陆·
//     next('/login')
//   } else if (to.meta.redirectAlreadyLogin && store.state.user.isLogin) {
//     next('/')
//   } else {
//     next()
//   }
// })
router.beforeEach(async (to, from, next) => {
  const token = store.state.token
  const username = store.state.user.nickName
  if (token) {
    axios.defaults.headers.common.Authorization = `Bearer ${token}`
    if (to.meta.redirectAlreadyLogin) {
      next('/')
    } else {
      if (username) {
        next()
      } else {
        try {
          await store.dispatch('fetchCurrentUser')
          next()
        } catch (e) {
          console.error(e)
          await store.commit('logout')
          next('/login')
        }
      }
    }
  } else {
    if (to.meta.requiredLogin) {
      next('/login?redirect=' + to.path)
    } else {
      next()
    }
  }

  //   if (to.meta.requiredLogin && !store.state.user.isLogin) {
  //     // 需要登陆，但没登陆·
  //     next('/login')
  //   } else if (to.meta.redirectAlreadyLogin && store.state.user.isLogin) {
  //     next('/')
  //   } else {
  //     next()
  //   }
})
export default router
